<?php
namespace  zhtfrontend\components\services\goods;

use common\components\helpers\Fun;
use yii\db\ActiveRecord;
use zhtfrontend\models\datas\ArtTeaching;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsPrice;
use yii\base\Action;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\widgets\ActiveForm;
use yii\web\Response;

class SetDistributionAction extends Action{

    public $type;

    public function run(){
//        $this->controller->layout=false;
        $goods_id = \Yii::$app->request->get('id');
        if ($goods_id == null) {
            throw new BadRequestHttpException(\Yii::t('frontend', '错误请求'));
        }
        $type = !empty(\Yii::$app->request->get('type_id')) ? \Yii::$app->request->get('type_id'):1;
        $this->type = $type;
        $modelgoods = Goods::findOne($goods_id);
        if ($modelgoods ==null) {
            throw new NotFoundHttpException(\Yii::t('frontend', '信息不存在'));
        }

        $goodsPrice = new GoodsPrice();
        $goodsPrice->is_frequency =1;
        $goodsPrice->goods_id =$goods_id;
        $goodsPrice->is_group =$modelgoods->is_group;
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $goodsPrice->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($goodsPrice);
        }

        if ($goodsPrice->load(\Yii::$app->request->post()) && $goodsPrice->validate()) {
            $goodsPrice->admin_id = \Yii::$app->user->id;
            $goodsPrice->activity_start_time = isset($goodsPrice->activity_start_time)?strtotime($goodsPrice->activity_start_time):0;
            $goodsPrice->activity_end_time = isset($goodsPrice->activity_end_time)?strtotime($goodsPrice->activity_end_time):0;
            if($goodsPrice->save(false)) {
                $modelgoods->is_update_price = 1;
                $modelgoods->status = 0;
                $modelgoods->is_shelve = 0;
                $modelgoods->save(false);
                $url = Fun::url([$this->controller->id . '/setlist', 'id' => $goods_id]);
//                if ($this->controller->id == 'goodsskill') {
//                    $url = Fun::url([$this->controller->id . '/setlist', 'id' => $goods_id]);
//                }
//                return $this->controller->redirectMessage('修改成功',$url);
                return $this->controller->redirectMessage(\Yii::t('zhtfrontend', '设置成功'), $url);
            }

        }
        return $this->controller->render('@zhtfrontend/components/services/goods/set.php',['data'=>$modelgoods,'model'=>$goodsPrice]);
    }

}